package com.cskaoyan.typeHandler;
/*
 * @Auther:王贲
 * @Date:2022/9/7
 * @Description:
 * @VERSON:1.8
 */

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.javassist.compiler.ast.Variable;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Integer[].class)//java类型
@MappedJdbcTypes(JdbcType.VARCHAR)//数据库类型
public class integerTypeHandler implements TypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement ps, int i, Integer[] Integers, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(Integers);
        ps.setString(i, value);
    }

    @Override
    public Integer[] getResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return transfer(result);
    }

    @SneakyThrows
    private Integer[] transfer(String resule) {
        Integer[] array = new Integer[0];
        if (resule == null || "".equals(resule)) {
            return array;
        }
        array = objectMapper.readValue(resule, Integer[].class);
        return array;
    }
}
